//
//  RegisterViewController.m
//  TeacherNet
//
//  Created by slz on 2017/12/18.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "RegisterViewController.h"
#import "NewWebViewController.h"
#import <IQKeyboardManager.h>
#import <YYText.h>
#import "MFWUserLoginManager.h"

#define kTextFiledBoderColor [UIColor colorWithRGB:0xb5b6b8]

typedef enum : NSUInteger {
    UserRegisterStateSuccess,
    UserRegisterStateNoPhone,
    UserRegisterStatePhoneError,
    UserRegisterStatePhoneExist,
    UserRegisterStateNoUserName,
    UserRegisterStateUserNameExist,
    UserRegisterStateNoPassword
} UserRegisterState;

@implementation RegisterTextFiled



- (CGRect)textRectForBounds:(CGRect)bounds{
    
    return CGRectInset(bounds, 8, 0);
    
}

//控制文本的位置
- (CGRect)editingRectForBounds:(CGRect)bounds{
    
    return CGRectInset(bounds, 8, 0);
}

@end

@interface RegisterViewController ()
@property (nonatomic,strong) TTScrollView *scrollView;
@property (nonatomic,strong) RegisterTextFiled *phoneTextF;
@property (nonatomic,strong) RegisterTextFiled *uNameTextF;
@property (nonatomic,strong) RegisterTextFiled *passwordTextFaaa;
@property (nonatomic,strong) RegisterTextFiled *passwordTextFbbb;
@property (nonatomic,strong) RegisterTextFiled *messageNumberText;
@property (nonatomic,strong) UILabel *getMessageButton; //用Label添加点击事件  UITap
@property (nonatomic,strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic,strong) UIButton *registerButton;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 120;
    self.showNavigationBar = YES;
    UIBarButtonItem * backItem = [UIBarButtonItem itemWithImage:@"back_icon" selectImage:@"" addTarget:self andAction:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = backItem;
    [self setControllerTitle:@"用户注册"];
    [self initSubView];
    // Do any additional setup after loading the view from its nib.
}


- (void)initSubView
{
    _scrollView = [[TTScrollView alloc]init];
    _scrollView.contentSize = CGSizeMake(kScreenWidth, 365);
    [self.view addSubview:_scrollView];
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    NSInteger leftRightMargin = 20;
    NSInteger titleFontSize = kFont_Size_Small_Title;
    UIFont * font = [UIFont systemFontOfSize:titleFontSize];
    NSInteger textFiledHeight = 46;
    
    UILabel * aaaLabel = [UILabel new];
    aaaLabel.text = @"手机号码";
    aaaLabel.textColor = kDark_TextColor_Default;
    aaaLabel.fontSize = titleFontSize;
    [_scrollView addSubview:aaaLabel];
    [aaaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftRightMargin);
        make.top.mas_equalTo(30);
    }];
    
    _phoneTextF = [RegisterTextFiled new];
    _phoneTextF.borderStyle = UITextBorderStyleNone;
    _phoneTextF.placeholder = @"用于登录或找回密码";
    _phoneTextF.font = font;
    _phoneTextF.layer.borderWidth = 1.5;
    _phoneTextF.layer.borderColor = kTextFiledBoderColor.CGColor;
    _phoneTextF.keyboardType = UIKeyboardTypeNumberPad;
    [_scrollView addSubview:_phoneTextF];
    [_phoneTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftRightMargin);
        make.top.mas_equalTo(aaaLabel.mas_bottom).offset(10);
        make.right.mas_equalTo(self.view.mas_right).offset(-leftRightMargin);
        make.height.mas_equalTo(textFiledHeight);
    }];
    
    UILabel * bbbLabel = [UILabel new];
    bbbLabel.text = @"用户名";
    bbbLabel.textColor = kDark_TextColor_Default;
    bbbLabel.fontSize = titleFontSize;
    [_scrollView addSubview:bbbLabel];
    [bbbLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftRightMargin);
        make.top.mas_equalTo(_phoneTextF.mas_bottom).offset(8);
    }];
    
    _uNameTextF = [RegisterTextFiled new];
    _uNameTextF.borderStyle = UITextBorderStyleNone;
    _uNameTextF.placeholder = @"不超过30个字符长度";
    _uNameTextF.font = font;
    _uNameTextF.layer.borderWidth = 1.5;
    _uNameTextF.layer.borderColor = kTextFiledBoderColor.CGColor;
    [_scrollView addSubview:_uNameTextF];
    [_uNameTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftRightMargin);
        make.top.mas_equalTo(bbbLabel.mas_bottom).offset(10);
        make.right.mas_equalTo(self.view.mas_right).offset(-leftRightMargin);
        make.height.mas_equalTo(textFiledHeight);
    }];
    
    UILabel * cccLabel = [UILabel new];
    cccLabel.text = @"密码";
    cccLabel.textColor = kDark_TextColor_Default;
    cccLabel.fontSize = titleFontSize;
    [_scrollView addSubview:cccLabel];
    [cccLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftRightMargin);
        make.top.mas_equalTo(_uNameTextF.mas_bottom).offset(8);
    }];
    
    _passwordTextFaaa = [RegisterTextFiled new];
    _passwordTextFaaa.borderStyle = UITextBorderStyleNone;
    _passwordTextFaaa.placeholder = @"6-30位英文、数字、符号，区分大小写";
    _passwordTextFaaa.font = font;
    _passwordTextFaaa.layer.borderWidth = 1.5;
    _passwordTextFaaa.layer.borderColor = kTextFiledBoderColor.CGColor;
    _passwordTextFaaa.secureTextEntry = YES;
    _passwordTextFaaa.keyboardType = UIKeyboardTypeASCIICapable;
    [_scrollView addSubview:_passwordTextFaaa];
    [_passwordTextFaaa mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftRightMargin);
        make.top.mas_equalTo(cccLabel.mas_bottom).offset(10);
        make.right.mas_equalTo(self.view.mas_right).offset(-leftRightMargin);
        make.height.mas_equalTo(textFiledHeight);
    }];
    
//    UILabel * dddLabel = [UILabel new];
//    dddLabel.text = @"确认密码";
//    dddLabel.textColor = kDark_TextColor_Default;
//    dddLabel.fontSize = titleFontSize;
//    [_scrollView addSubview:dddLabel];
//    [dddLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(leftRightMargin);
//        make.top.mas_equalTo(_passwordTextFaaa.mas_bottom).offset(8);
//    }];
    
//    _passwordTextFbbb = [RegisterTextFiled new];
//    _passwordTextFbbb.borderStyle = UITextBorderStyleNone;
//    _passwordTextFbbb.placeholder = @"再次输入密码";
//    _passwordTextFbbb.font = font;
//    _passwordTextFbbb.layer.borderWidth = 1.5;
//    _passwordTextFbbb.layer.borderColor = kTextFiledBoderColor.CGColor;
//    _passwordTextFbbb.secureTextEntry = YES;
//    _passwordTextFbbb.keyboardType = UIKeyboardTypeASCIICapable;
//    [_scrollView addSubview:_passwordTextFbbb];
//    [_passwordTextFbbb mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(leftRightMargin);
//        make.top.mas_equalTo(dddLabel.mas_bottom).offset(10);
//        make.right.mas_equalTo(self.view.mas_right).offset(-leftRightMargin);
//        make.height.mas_equalTo(textFiledHeight);
//    }];
    
//    UILabel * eeeLabel = [UILabel new];
//    eeeLabel.text = @"短信验证码";
//    eeeLabel.textColor = kDark_TextColor_Default;
//    eeeLabel.fontSize = titleFontSize;
//    [_scrollView addSubview:eeeLabel];
//    [eeeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(leftRightMargin);
//        make.top.mas_equalTo(_passwordTextFbbb.mas_bottom).offset(8);
//    }];
//
//    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(timeAction)];
//
//    _getMessageButton = [UILabel new];
//    _getMessageButton.text = @"获取短信验证码";
//    _getMessageButton.textAlignment = NSTextAlignmentCenter;
//    _getMessageButton.fontSize = titleFontSize;
//    _getMessageButton.layer.borderWidth = 1.5;
//    _getMessageButton.layer.borderColor = kTextFiledBoderColor.CGColor;
//    _getMessageButton.userInteractionEnabled = YES;
//    [_getMessageButton addGestureRecognizer:tap];
//    _getMessageButton.backgroundColor = [UIColor colorWithRGB:0xF5F5F6];
//    _getMessageButton.textColor = [UIColor colorWithRGB:0x919394];
//    [_scrollView addSubview:_getMessageButton];
//    [_getMessageButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.size.mas_equalTo(CGSizeMake(130, textFiledHeight));
//        make.right.mas_equalTo(self.view.mas_right).offset(-leftRightMargin);
//        make.top.mas_equalTo(eeeLabel.mas_bottom).offset(10);
//    }];
//
//    _indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//    _indicatorView.hidesWhenStopped = YES;
//    [_getMessageButton addSubview:_indicatorView];
//    [_indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.mas_equalTo(_getMessageButton);
//    }];
//
//    _messageNumberText = [RegisterTextFiled new];
//    _messageNumberText.borderStyle = UITextBorderStyleNone;
//    _messageNumberText.placeholder = @"验证码";
//    _messageNumberText.font = font;
//    _messageNumberText.layer.borderWidth = 1.5;
//    _messageNumberText.layer.borderColor = kTextFiledBoderColor.CGColor;
//    _messageNumberText.secureTextEntry = YES;
//    _messageNumberText.keyboardType = UIKeyboardTypePhonePad;
//    [_scrollView addSubview:_messageNumberText];
//    [_messageNumberText mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(leftRightMargin);
//        make.top.mas_equalTo(eeeLabel.mas_bottom).offset(10);
//        make.right.mas_equalTo(_getMessageButton.mas_left).offset(-10);
//        make.height.mas_equalTo(textFiledHeight);
//    }];
    
    
    @weakify(self);
    NSMutableAttributedString *all = [NSMutableAttributedString new];
    NSMutableAttributedString *two = [[NSMutableAttributedString alloc] initWithString:@"说明：注册/登录代表您已同意"];
    two.yy_font = [UIFont boldSystemFontOfSize:12];
    two.yy_color = kDark_TextColor_Default;

    NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString:@"《服务协议》"];
    one.yy_font = [UIFont boldSystemFontOfSize:12];
    one.yy_color = kLoginGreenColor;
    one.yy_underlineColor = one.yy_color;
    one.yy_underlineStyle = NSUnderlineStyleSingle;

    YYTextHighlight *highlight = [YYTextHighlight new];
    [highlight setColor:[UIColor whiteColor]];
    highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
        @strongify(self);
        [self jumpToProtocolWeb];
    };
    [one yy_setTextHighlight:highlight range:one.yy_rangeOfAll];

    [all appendAttributedString:two];
    [all appendAttributedString:one];

    YYLabel * label = [YYLabel new];
    label.attributedText = all;
    label.textAlignment = NSTextAlignmentLeft;
    label.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    label.numberOfLines = 0;
    [_scrollView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_scrollView.mas_left).offset(leftRightMargin);
        make.width.mas_equalTo(kScreenWidth - 2*leftRightMargin);
        make.top.mas_equalTo(_passwordTextFaaa.mas_bottom).offset(15);
        make.height.mas_equalTo(20);
    }];
    
    
    _registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _registerButton.backgroundColor = kLoginGreenColor;
    [_registerButton setTitle:@"注   册" forState:UIControlStateNormal];
    [_registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _registerButton.titleLabel.fontSize = titleFontSize;
    [_registerButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        @strongify(self);
        [self registerAction];
    }];
    [_scrollView addSubview:_registerButton];
    [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftRightMargin);
        make.right.mas_equalTo(self.view.mas_right).offset(-leftRightMargin);
        make.height.mas_equalTo(textFiledHeight);
        make.top.mas_equalTo(label.mas_bottom).offset(35);
    }];
}

- (BOOL)validateNumber:(NSString *)textString
{
    if (textString.length != 11){
        return NO;
    }
    NSString* number=@"^[0-9]+$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}

- (void)registerAction
{
    NSString * phoneString = _phoneTextF.text;
    if (![self validateNumber:phoneString]){
        [self.view showTip:@"请输入正确的手机号码~"];
        return;
    }
    NSString * userName = _uNameTextF.text;
    if (userName == nil || userName.length == 0){
        [self.view showTip:@"请输入用户名~"];
        return;
    }
    if (userName.length > 30){
        [self.view showTip:@"用户名长度超过30~"];
        return;
    }
    NSString * password = _passwordTextFaaa.text;
    if (password == nil || password.length == 0){
        [self.view showTip:@"请输入密码~"];
        return;
    }
    if (password.length < 6){
        [self.view showTip:@"密码长度小于6~"];
        return;
    }
    if (password.length > 30){
        [self.view showTip:@"密码长度超过30~"];
        return;
    }
    [SVProgressHUD showWithStatus:@"注册中..."];
    
//    [[MFWUserLoginManager sharedInstance] registerWithOIDUserName:userName password:password email:phoneString finisheHandler:^(BOOL success, MFWUserInfo *userInfo, NSError *error) {
//
//    }];
    
    [BaseHttpTool get:kAPI_REGISTER_USER params:@{@"phone":phoneString,@"username":userName,@"password":password} success:^(id responseObj) {
        [SVProgressHUD dismiss];
        MFWJson * json = [MFWJson jsonWithObject:responseObj];
        [self handleResultJson:json];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}


- (void)handleResultJson:(MFWJson *)json
{
    UserRegisterState state = [json intValueForKey:@"status"];
    NSString * msg = [json stringValueForKey:@"msg"];
    if (state == UserRegisterStateSuccess){
        [self.view showTip:msg completion:^{
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else
    {
        [SVProgressHUD showErrorWithStatus:msg];
    }
}

- (void)jumpToProtocolWeb
{
    NewWebViewController * web = [[NewWebViewController alloc]init];
    web.url = @"http://www.youyuwei.com/protocal-account.html";
    [self.navigationController pushViewController:web animated:YES];
}

- (void)timeAction{
    _getMessageButton.text = @"";
    [_indicatorView startAnimating];
    _getMessageButton.exclusiveTouch = YES;
    _getMessageButton.userInteractionEnabled = NO;
    [BaseHttpTool get:kAPI_HOME_COURSE params:@{} success:^(id responseObj) {
        [_indicatorView stopAnimating];
        [self timeStart];
    } failure:^(NSError *error) {
        [self.view showTip:error.localizedDescription];
        self.getMessageButton.userInteractionEnabled = YES;
    }];
}

- (void)timeStart{
    __block int time = 5;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (time < 1){
            dispatch_source_cancel(_timer);// gcd timer中必须要有 cancle 这个timer的代码 否则代码将无法执行。
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString * defaultTimeString = @"获取验证码";
                self.getMessageButton.text = defaultTimeString;
                self.getMessageButton.userInteractionEnabled = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                time--;
                NSString *timeString = [NSString stringWithFormat:@"%d",time];
                self.getMessageButton.text = timeString;
            });
        }
    });
    dispatch_resume(_timer);
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
